package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	pb "helloworld/helloworld"
	"io"
	"log"
	"math/rand"
	"net"
)

type server struct {
	pb.UnimplementedGreeterServer
}

func (s server) SayHello(ctx context.Context, request *pb.HelloRequest) (*pb.HelloReply, error) {
	log.Println("【Method SayHello】received:", request)
	msg := fmt.Sprintf("Name:%s;Age:%d", request.Name, int(request.Age))
	reply := &pb.HelloReply{
		Message: msg,
	}
	return reply, nil
}

func (s server) RequestVideo(videoServer pb.Greeter_RequestVideoServer) error {
	for {
		req, err := videoServer.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		log.Println("【Method RequestVideo】received:", req)

		resp := new(pb.VideoResponse)
		resp.Name = req.Name
		resp.Url = fmt.Sprintf("http:%s/%s", req.Name, req.Tag)
		resp.TimeLength = int64(rand.Intn(20))
		if err := videoServer.Send(resp); err != nil {
			return err
		}
	}

}

func main() {
	address := "localhost:8009"
	lis, err := net.Listen("tcp", address)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, newServer())
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

func newServer() pb.GreeterServer {
	return &server{}
}
